package com.swh.cloud.biz.controll;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;

/**
 * 此方法 只为测试用， 从Eureka Server发现服务实例
 * 
 * @author sangwenhao-桑文豪
 * @date 2016年12月25日 下午10:15:28
 */
@Component
@RestController
@RequestMapping(value = "/discoveryClient")
public class DiscoverClientControll {

	// 从 Eureka Server发现服务实例

	// eureka原始的方式
	// 不要在@PostConstruct方法或@Scheduled方法使用EurekaClient（或任何ApplicationContext还没被启动的地方）。
	@Autowired
	private EurekaClient discoveryEurekaClient;

	@RequestMapping("/serviceUrlByEureka")
	public String serviceUrl() {
		InstanceInfo instance = discoveryEurekaClient.getNextServerFromEureka(
				"user-cloud-biz-service", false);
		return instance.getHomePageUrl();
	}

	// spring 封装后的方式
	@Autowired
	private DiscoveryClient discoveryClient;

	@RequestMapping("/serviceUrlbySpring")
	public String serviceUrlbySpring() {
		List<ServiceInstance> list = discoveryClient.getInstances("user-cloud-biz-service");
		if (list != null && list.size() > 0) {
			return list.get(0).getUri().toString();
		}
		return null;
	}

	//spring的方式
	@RequestMapping("/discovery")
	public String doDiscoveryService() {
		StringBuilder buf = new StringBuilder();
		List<String> serviceIds = discoveryClient.getServices();
		if (!CollectionUtils.isEmpty(serviceIds)) {
			for (String s : serviceIds) {
				System.out.println("serviceId:" + s);
				List<ServiceInstance> serviceInstances = discoveryClient
						.getInstances(s);
				if (!CollectionUtils.isEmpty(serviceInstances)) {
					for (ServiceInstance si : serviceInstances) {
						buf.append("[" + si.getServiceId() + " host="
								+ si.getHost() + " port=" + si.getPort()
								+ " uri=" + si.getUri() + "]");
					}
				} else {
					buf.append("no service.");
				}
			}
		}
		return buf.toString();
	}

}
